<template>
  <div>
    <el-form ref="cateAdd" :rules="rules" :model="cate" label-width="80px">
      <el-form-item label="分类名称" prop="cateName">
        <el-input v-model="cate.cateName"></el-input>
      </el-form-item>
      <el-form-item label="父级">
        <el-select v-model="cate.pid" placeholder="请选择父级分类">
          <el-option
            v-for="cate in cates"
            :key="cate.id"
            :label="cate.cateName"
            :value="cate.id"
          ></el-option>
          <el-option label="顶层分类" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类图标">
        <el-upload
          class="upload-demo"
          name="file"
          action="/api/upload"
          :on-success="uploadSuccess"
          :on-error="uploadFail"
          :before-upload="beforeUpload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
        <img :src="cate.icon" width="100" alt="">
      </el-form-item>
      <el-form-item label="是否启用">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="cate.usable"
        ></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    cates: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      cate: {
        cateName: '',
        pid: 0, // 0顶层分类
        icon: '',
        usable: 1
      },
      rules: {
        cateName: [
          {
            required: true,
            // 验证不通过时，错误提示文案
            message: '当前字段是必填的'
          }
        ]
      }
    }
  },
  methods: {
    beforeUpload (file) {
      // 上传文件之前  限制上传文件的体积
      if (file.size > (1024 * 1024 * 5)) {
        this.$message({
          type: 'error',
          message: '请上传小于5M体积的图标'
        })
        return false
      } else {
        return true
      }
    },
    uploadSuccess (res) {
      // 上传成功
      // 弹出成功提示
      this.$message({
        type: 'success',
        message: '图片上传成功'
      })
      this.cate.icon = res.data.url
    },
    uploadFail () {
      // 上传失败
    },
    onSubmit () {
      this.$refs.cateAdd.validate((valid) => {
        if (valid) {
          // 验证通过
          this.$emit('addCate', this.cate)
        } else {
          // 验证不通过
          this.$message({
            type: 'error',
            message: '表单验证不通过'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
